package main

import (
	"fmt"
	"ghw2/server/config"
	"ghw2/server/redis"
	"ghw2/server/register"
	"ghw2/server/service"
	"net"
	"time"
)

func heartBeat(conn *net.Conn) {
	data := "ping"
	(*conn).Write([]byte(data))
}

func main() {
	if err := redis.InitRedis(); err != nil {
		fmt.Println(err)
		return
	}
	if err := config.ServerConfigInit("server.yaml"); err != nil {
		return
	}

	conn, err := register.RegisterServiceToNameServer()

	if err != nil {
		return
	}

	defer (*conn).Close()

	ticker := time.NewTicker(5 * time.Second)

	// 资源释放
	defer ticker.Stop()

	// 心跳协程
	go func() {
		for range ticker.C {
			heartBeat(conn)
		}
	}()

	if listener, err := net.Listen("tcp", config.ServerConfig.Server); err != nil {
		return
	} else {
		fmt.Println("Now server is listening at address", listener.Addr().String(), ":")
		if err := service.RegisterService(listener); err != nil {
			return
		}
	}

}
